<template>
  <div class="template-page gradient-bg">
    <!-- 顶部栏：返回首页 + 标题 -->
    <div class="topbar glass">
      <button class="back-btn" @click="goHome">← 返回首页</button>
      <h2 class="title">模板管理</h2>
    </div>

    <div class="layout">
      <!-- 左侧：分类列表 -->
      <div class="sidebar glass" @mouseleave="hoverCat = null">
        <div class="sidebar-header">模板分类</div>
        <div
          v-for="cat in categories"
          :key="cat"
          class="cat-item"
          @mouseenter="hoverCat = cat"
        >
          <div class="cat-row">
            <button
              class="cat-name"
              @click="toggleCat(cat)"
              :class="{ selected: selected.category === cat }"
            >
              {{ cat }}
            </button>
            <div class="cat-actions" v-if="hoverCat === cat">
              <button class="more-btn" @click="toggleCatMenu(cat)">⋯</button>
              <transition name="fade">
                <button
                  v-if="catMenu === cat"
                  class="del-cat-btn"
                  @click="deleteCategory(cat)"
                >
                  删除分类
                </button>
              </transition>
            </div>
          </div>
          <transition name="accordion">
            <div v-show="expanded[cat]" class="templates-list">
              <button
                v-for="t in templates[cat] || []"
                :key="t"
                class="tpl-name"
                @click="selectTemplate(cat, t)"
                :class="{
                  selected: selected.category === cat && selected.name === t,
                }"
              >
                {{ t }}
              </button>
            </div>
          </transition>
        </div>
      </div>

      <!-- 中间：预览区 -->
      <div class="content glass">
        <div class="preview" v-if="selected.category && selected.name">
          <button
            class="delete-btn"
            @click="deleteTemplate(selected.category, selected.name)"
          >
            删除模板
          </button>
          <div class="preview-center">
            <img v-if="imgSrc" :src="imgSrc" alt="模板预览" />
            <div v-else class="placeholder">请选择左侧模板名称查看预览</div>
          </div>
        </div>
        <div v-else class="empty-preview glass subtle">请选择左侧模板名称</div>

        <!-- 右侧：上传表单 -->
        <div class="upload glass">
          <h3>上传模板图片</h3>
          <form @submit.prevent="onUpload">
            <div class="form-row">
              <label>应用名称</label>
              <input
                v-model="form.category"
                required
                placeholder="例如：微信、酷狗音乐"
              />
            </div>
            <div class="form-row">
              <label
                >模板图片名称规范：控件名称-事件(click,doubleClick,input)</label
              >
              <input
                v-model="form.name"
                required
                placeholder="示例：播放-click"
              />
            </div>
            <div class="form-row">
              <label>选择图片</label>
              <input
                ref="fileInput"
                type="file"
                accept="image/*"
                @change="onFileChange"
                required
              />
            </div>
            <div class="form-actions">
              <button type="submit" class="primary">上传</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "TemplateView",
  data() {
    return {
      categories: [],
      templates: {},
      expanded: {},
      hoverCat: null,
      catMenu: null,
      selected: { category: "", name: "" },
      imgSrc: "",
      form: { category: "", name: "", file: null, mime: "" },
    };
  },
  created() {
    this.refreshCategories();
  },
  methods: {
    goHome() {
      this.$router.push("/");
    },
    async refreshCategories() {
      const res = await window.electronTemplateAPI.listCategories();
      if (res && res.success) {
        this.categories = res.categories || [];
        for (const cat of this.categories) {
          await this.loadTemplates(cat);
        }
      }
    },
    async loadTemplates(cat) {
      const res = await window.electronTemplateAPI.listTemplates(cat);
      if (res && res.success) {
        this.$set(this.templates, cat, res.templates || []);
      }
    },
    toggleCat(cat) {
      this.$set(this.expanded, cat, !this.expanded[cat]);
    },
    toggleCatMenu(cat) {
      this.catMenu = this.catMenu === cat ? null : cat;
    },
    async deleteCategory(cat) {
      if (!confirm(`确认删除分类「${cat}」及其下所有模板吗？`)) return;
      const res = await window.electronTemplateAPI.deleteCategory(cat);
      if (res && res.success) {
        this.categories = this.categories.filter((c) => c !== cat);
        this.$delete(this.templates, cat);
        this.$delete(this.expanded, cat);
        if (this.selected.category === cat) {
          this.selected = { category: "", name: "" };
          this.imgSrc = "";
        }
      } else {
        alert(res.error || "删除分类失败");
      }
      this.catMenu = null;
    },
    async selectTemplate(cat, name) {
      this.selected = { category: cat, name };
      const res = await window.electronTemplateAPI.getTemplateDataURL(
        cat,
        name
      );
      this.imgSrc = res && res.success ? res.dataURL : "";
    },
    async deleteTemplate(cat, name) {
      if (!confirm(`确认删除模板「${name}」吗？`)) return;
      const res = await window.electronTemplateAPI.deleteTemplate(cat, name);
      if (res && res.success) {
        await this.loadTemplates(cat);
        if (this.selected.category === cat && this.selected.name === name) {
          this.selected = { category: "", name: "" };
          this.imgSrc = "";
        }
      } else {
        alert(res.error || "删除模板失败");
      }
    },
    onFileChange(e) {
      const f = e.target.files && e.target.files[0];
      this.form.file = f || null;
      this.form.mime = (f && f.type) || "";
    },
    async onUpload() {
      if (!this.form.file) {
        alert("请选择图片");
        return;
      }
      const category = (this.form.category || "").trim();
      const name = (this.form.name || "").trim();
      if (!category || !name) {
        alert("请填写完整信息");
        return;
      }
      const dataURL = await this.readFileAsDataURL(this.form.file);
      const res = await window.electronTemplateAPI.saveTemplate({
        category,
        name,
        data: dataURL,
        mime: this.form.mime,
      });
      if (res && res.success) {
        if (!this.categories.includes(category)) this.categories.push(category);
        await this.loadTemplates(category);
        this.$set(this.expanded, category, true);
        this.form = { category: "", name: "", file: null, mime: "" };
        if (this.$refs.fileInput) {
          this.$refs.fileInput.value = "";
        }
      } else {
        alert(res.error || "上传失败");
      }
    },
    readFileAsDataURL(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    },
  },
};
</script>

<style scoped>
.select-file {
  display: inline-block;
  padding: 8px 12px;
  background: linear-gradient(135deg, #fde68a, #fecaca);
  color: #333;
  border-radius: 8px;
  cursor: pointer;
}

/* 背景渐变，体现层次感 */
.gradient-bg {
  min-height: 100vh;
  box-sizing: border-box;
  padding: 20px 0;
  background: radial-gradient(circle at 20% 10%, #ff6ec7 0%, transparent 40%),
    radial-gradient(circle at 80% 20%, #6ee7ff 0%, transparent 45%),
    radial-gradient(circle at 30% 80%, #fff59d 0%, transparent 50%),
    linear-gradient(135deg, #c3dafe 0%, #fbcfe8 100%);
}

/* 玻璃态卡片 */
.glass {
  background: rgba(255, 255, 255, 0.35);
  border: 1px solid rgba(255, 255, 255, 0.4);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(12px);
  border-radius: 16px;
}
.subtle {
  background: rgba(255, 255, 255, 0.25);
}

.topbar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  margin: 0 20px 16px;
}
.title {
  margin: 0;
  font-weight: 700;
  letter-spacing: 0.5px;
}
.back-btn {
  background: transparent;
  border: none;
  color: #333;
  font-weight: 600;
  cursor: pointer;
}

.layout {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 20px;
  padding: 0 20px 20px;
}

.sidebar {
  padding: 14px;
}
.sidebar-header {
  font-weight: 700;
  margin-bottom: 8px;
}
.cat-item {
  margin-bottom: 8px;
}
.cat-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}
.cat-name {
  flex: 1;
  text-align: left;
  background: rgba(255, 255, 255, 0.6);
  border: 1px solid rgba(0, 0, 0, 0.05);
  padding: 8px 10px;
  border-radius: 10px;
  cursor: pointer;
}
.cat-name.selected {
  background: linear-gradient(135deg, #fde68a, #fecaca);
  border-color: rgba(245, 158, 11, 0.35);
  box-shadow: 0 8px 20px rgba(245, 158, 11, 0.22);
}
.cat-actions {
  display: flex;
  align-items: center;
  gap: 6px;
}
.more-btn {
  width: 28px;
  height: 28px;
  border-radius: 8px;
  border: none;
  background: rgba(0, 0, 0, 0.06);
  cursor: pointer;
}
.del-cat-btn {
  background: #ef4444;
  color: #fff;
  border: none;
  padding: 6px 10px;
  border-radius: 8px;
}
.templates-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 6px 0 6px 8px;
}
.tpl-name {
  text-align: left;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.05);
  padding: 6px 10px;
  border-radius: 8px;
  cursor: pointer;
}
.tpl-name.selected {
  background: linear-gradient(135deg, #dbeafe, #ede9fe);
  border-color: rgba(111, 66, 193, 0.35);
  box-shadow: 0 8px 20px rgba(111, 66, 193, 0.22);
}

.content {
  display: grid;
  grid-template-columns: 1fr 340px;
  gap: 20px;
  padding: 14px;
}

.preview {
  position: relative;
  min-height: 360px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.delete-btn {
  position: absolute;
  right: 12px;
  top: 12px;
  background: #e33;
  color: #fff;
  border: none;
  padding: 6px 10px;
  border-radius: 8px;
  box-shadow: 0 10px 20px rgba(227, 51, 51, 0.25);
}
.preview-center {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 12px;
}
.empty-preview {
  min-height: 360px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

.upload {
  padding: 12px;
}
.upload h3 {
  margin: 4px 0 12px;
}
.form-row {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
}
.form-row label {
  font-size: 12px;
  color: #555;
  margin-bottom: 4px;
}
/* 恢复通用输入框样式（文本输入、占位等） */
.form-row input {
  padding: 8px 10px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.7);
}

/* 文件选择控件的专用样式 */
.form-row input[type="file"] {
  padding: 6px 10px;
}
.form-row input[type="file"]::file-selector-button {
  background: #6f42c1;
  color: #fff;
  border: none;
  padding: 8px 14px;
  border-radius: 10px;
  box-shadow: 0 10px 20px rgba(111, 66, 193, 0.25);
  margin-right: 10px;
  cursor: pointer;
}
.form-row input[type="file"]::file-selector-button:hover {
  filter: brightness(1.05);
}
.form-row input[type="file"]::-webkit-file-upload-button {
  background: #6f42c1;
  color: #fff;
  border: none;
  padding: 8px 14px;
  border-radius: 10px;
  box-shadow: 0 10px 20px rgba(111, 66, 193, 0.25);
  margin-right: 10px;
  cursor: pointer;
}
.form-row input[type="file"]::-webkit-file-upload-button:hover {
  filter: brightness(1.05);
}
.form-actions {
  text-align: right;
}
.form-actions .primary {
  background: #6f42c1;
  color: #fff;
  border: none;
  padding: 8px 14px;
  border-radius: 10px;
  box-shadow: 0 10px 20px rgba(111, 66, 193, 0.25);
}

/* 动效 */
.accordion-enter-active,
.accordion-leave-active {
  transition: all 0.2s ease;
}
.accordion-enter,
.accordion-leave-to {
  opacity: 0;
  transform: translateY(-5px);
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.15s ease;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>






